package org.kingtop.shiro.exception;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 用于显示默认的错误消息
 *
 * @author 陈金波
 * @date 2018/2/27 21:17
 */
public enum ShiroExceptionEnum {

    DEFAULT_EXCEPTION(AuthenticationException.class, "其他错误"),
    VERIFY_CODE_EXCEPTION(VerifyCodeException.class, "验证码错误"),
    EXPIRED_CREDENTIAL_EXCEPTION(ExpiredCredentialsException.class, "登录超时，请重新登录"),
    AUTHENTICATION_EXCEPTION(AuthenticationException.class, "用户名/密码错误"),
    INCORRECT_CREDENTICALS_EXCEPTION(IncorrectCredentialsException.class, "用户名/密码错误"),
    UNKNOWN_ACCOUNT_EXCEPTION(UnknownAccountException.class, "用户名/密码错误"),
    LOCKED_ACCOUNT_EXCEPTION(LockedAccountException.class, "账户被锁定"),
    DISABLED_ACCOUNT_EXCEPTION(DisabledAccountException.class, "帐号已经被禁用"),
    EXCESSIVE_ATTEMPTS_EXCEPTION(ExcessiveAttemptsException.class, "登录失败次数过多，请稍后再试");

    ShiroExceptionEnum(Class<?> targetClass, String message) {
        this.message = message;
        this.targetClass = targetClass;
    }

    /**
     * 异常类
     */
    private Class<?> targetClass;

    /**
     * 消息
     */
    private String message;

    private static final Map<String, ShiroExceptionEnum> map = new HashMap<>();

    static {
        Arrays.stream(ShiroExceptionEnum.values()).forEach(item -> map.put(item.getTargetClass().getName(), item));
    }

    /**
     * 通过异常名称获取枚举
     *
     * @param name 异常名称
     * @return 枚举
     */
    public static Optional<ShiroExceptionEnum> getByClassName(String name) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        return Optional.ofNullable(map.get(name));
    }

    public Class<?> getTargetClass() {
        return targetClass;
    }

    public String getMessage() {
        return message;
    }

}
